package sax;

import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Node;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import dom.pojo.Book;

public class BooksHandler extends DefaultHandler{
	private List<Book> books;
	private Book book;
	private String node;
	private boolean tag=false;

	@Override
	public void startDocument() throws SAXException {
		books = new ArrayList<Book>();
	}

	@Override
	public void endDocument() throws SAXException {
		super.endDocument();
		for(Book book:books){
			System.out.println(book.toString());
		}
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		super.startElement(uri, localName, qName, attributes);
		tag=true;
		if(qName.equals("book")){
			book = new Book();
			book.setType(attributes.getValue("Type"));
			book.setIsbn(attributes.getValue("ISBN"));
		}
		node = qName;
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		super.endElement(uri, localName, qName);
		tag=false;
		if(qName.equals("book")){
		books.add(book);
		}
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		super.characters(ch, start, length);
		if(!tag){
			return;
		}
		
		String string = new String(ch, start, length);
		System.out.println(node);
		switch (node) {
		case "title":
			book.setTitle(string);
			break;
		case "author":
			book.setAuthor(string);
			break;
		case "price":
			book.setPrice(string);
			break;
		default:
			break;
		}
	
	}
	

}
